<template>
    <div class="plupload">
    <!-- {{uploader}} -->
        <!-- {{initionData}} -->
        <!-- 文本显示 -->
        <div v-if="displaymode == 'text'">
            <div style="width:100%">
                <template v-for="item in postData">
                        <div class="upload-item_text clearfix" :object = 'item.object'>
                            <div class="fl"><a class="tit" href="JavaScript:void(0);" :title="item.fileRealName">{{item.fileRealName}}</a></div>
                            <div class="fr">
                                <a class="text_link percent" href="JavaScript:void(0);" style="color:#67C23A"><i class="el-icon-circle-check"></i></a>
                                <a class="text_link" href="JavaScript:void(0);" @click="fileItemDelete(item.fileId,item.object,item.bucket)">删除</a>
                                <a class="text_link" href="JavaScript:void(0);" @click="download(item.object)">下载</a>
                                <el-button size="mini" @click="handleCopy(item.url)">复制地址</el-button>
                            </div>
                        </div>
                </template>
                <template v-for="item in previewData">
                    <div class='upload-item_text clearfix' :id="item.fileId">
                        <div class="fl"><a class="tit" href="JavaScript:void(0);" :title="item.fileRealName">{{item.fileRealName}}</a></div>
                        <div class="fr">
                            <a class="text_link percent" href="JavaScript:void(0);" v-if="item.percent != 100" style="color:#CCC">待上传</a>
                            <a class="text_link" href="JavaScript:void(0);" @click="fileItemDelete(item.fileId,item.object,item.bucket)">删除</a>
                            <a class="text_link" href="JavaScript:void(0);" @click="download(item.object)">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>
                        </div>
                    </div>
                </template>
            </div>
        </div>
        <!-- 图片显示 -->
        <div v-if="displaymode == 'images'">
            <!-- {{postData}} -->
            <div style="width:100%">
                <template v-for="item in postData">
                    <div class='thumbnail upload-item' :object='item.object' onmouseover='$(this).find(".cover-show").stop().slideDown(200);' onmouseleave='$(this).find(".cover-show").stop().slideUp(200);'>
                        <div class='cover-show'><span>{{item.fileRealName}}</span></div>
                        <template v-if="item.isImage">
                            <img :src='item.url' alt='' style='width:230px;height:140px;object-fit: cover;'>
                        </template>

                        <template v-else>
                            <img src="/static/js/plupload/suffix/otherfile.png" alt='' style='width:230px;height:140px;object-fit: cover;'>
                        </template>

                        <div class='caption'>
                            <div class='progress' style='visibility: hidden'><div class='progress-bar' style='width: 0%'></div></div>
                                <p>
                                    <el-button  size="mini" type="danger" @click="fileItemDelete(item.fileId,item.object,item.bucket)">删除</el-button>
                                    <el-button  size="mini"  @click="download(item.object)">下载</el-button>
                                    <el-button size="mini" @click="handleCopy(item.url)">复制地址</el-button>
                                </p>
                            </div>
                            <template v-if="!item.isImage">
                                <div style='position: absolute;left:90px;top:60px;font-size: 20px;color:#fff'>
                                    {{item.fileType}}</div>
                            </template>
                        </div>
                </template>
            </div>
            <div style="width:100%" >
                <template v-for="item in previewData">
                    <div class='thumbnail upload-item' :id="item.fileId" onmouseover='$(this).find(".cover-show").stop().slideDown(200);' onmouseleave='$(this).find(".cover-show").stop().slideUp(200);'>
                        <div class='cover-show'><span>{{item.fileRealName}}</span></div>
                        <img :src='item.imgsrc' alt='' style='width:230px;height:140px;object-fit: cover;'>
                        <div class='caption'>
                            <div class='progress'>
                                <div class='progress-bar' :style="{ 'width': 2*item.percent + '%' }" :aria-valuenow="item.percent"></div>
                            </div>
                            <p>
                                <el-button size="mini" type="danger" @click="fileItemDelete(item.fileId,item.object,item.bucket)">删除</el-button>
                                <b class='percent'><span v-if="item.percent > 0">{{item.percent}}%</span></b>
                                <!-- <el-button size="mini" @click="handleCopy(item.url)">复制</el-button> -->
                            </p>
                        </div>
                        <template v-if="!item.isImage">
                            <div  style='position: absolute;left:90px;top:60px;font-size: 20px;color:#fff'>{{item.fileType}}</div>
                        </template>
                    </div>
                </template>
          </div>
        </div>
          <div style="clear: both;"></div>
          <div :id="buttonIds.container">
            <el-button type="primary" size="mini" :id="buttonIds.select">选择文件</i></el-button>
            <el-button type="primary" size="mini" :id="buttonIds.upload">上传<i class="el-icon-upload el-icon--right"></i></el-button>
          </div>
    </div>
</template>


<script>
    import PlUpload from "../../static/js/plupload/plupload.full.min";
    import { get_upload_param } from "../../static/js/plupload/upparams";
    import { config as appConfig } from "@/config.js";
    export default {
        components: {
            PlUpload
        },
        data: function() {
            return {
                /*postData: [],*/
                previewData: [], //  页面预显示数据
                uploader: {}, //上传对象
            };
        },
        watch: {
            postData: function(val) {
                console.log(111111);
                console.log(val);
                
                if (val && val.length > 0) {
                    for (let i = 0; i < val.length; i++) {
                        let item = this.postData[i];
                        this.postData[i]["isImage"] = true;

                        // item.fileType = item.fileType ? item.fileType : item.fileRealName.splice('.')[1];
                        // console.log(item.fileType ? item.fileType : item.fileRealName.splice('.')[1]);

                        if ( $.inArray(item.fileType, ["jpg", "jpeg",,"image/jpeg", "gif", "png", "bmp"]) < 0 ) {
                            this.postData[i]["isImage"] = false;
                            this.postData[i]["previewImg"] = "/static/js/plupload/suffix/otherfile.png";
                        }
                    }
                    // this.postData = this.initionData;
                }
            }
        },
        props: {
            postData: {
                default: []
            },
            displaymode: {
                default: "images"
            },
            multiFile: {
                default: true
            },
            api: {
                default: true
            },
            imageOnly: {
                default: false
            },
            extensions: {
                default: ""
            },
            buttonIds: {
                default: function() {
                    return {
                        select: "selectfiles",
                        upload: "postfiles",
                        container: "container"
                    };
                }
            }
        },
        methods: {
            // 预览图片处理
            previewImage: function(file, callback) {
                if (!/image\//.test(file.type)) {
                    var name = file.name;
                    var pos = name.lastIndexOf(".");
                    var suffix = name.substring(pos + 1);
                    callback && callback("/static/js/plupload/suffix/otherfile.png", suffix);
                    return;
                }
                if (file.type == "image/gif") {
                    //gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
                    var fr = new mOxie.FileReader();
                    fr.onload = function() {
                        callback(fr.result, false);
                        fr.destroy();
                        fr = null;
                    };
                    fr.readAsDataURL(file.getSource());
                } else {
                    var preloader = new mOxie.Image();
                    preloader.onload = function() {
                        preloader.downsize(300, 300); //先压缩一下要预览的图片,宽300，高300
                        var imgsrc =
                            preloader.type == "image/jpeg" ?
                            preloader.getAsDataURL("image/jpeg", 80) :
                            preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
                        callback && callback(imgsrc, true); //callback传入的参数为预览图片的url
                        preloader.destroy();
                        preloader = null;
                    };
                    preloader.load(file.getSource());
                }
            },
            // 初始化文件格式
            initFilters: function() {
                if (this.extensions) {
                    return [{
                        title: "definedExtensions",
                        extensions: this.extensions
                    }];
                } else {
                    let filters = [{
                        title: "Image files",
                        extensions: "jpg,jpeg,gif,png,bmp"
                    }];
                    if (!this.imageOnly) {
                        filters.push({
                            title: "Zip files",
                            extensions: "zip,rar"
                        });
                        filters.push({
                            title: "Doc files",
                            extensions: "doc,xls,xlsx,docx,ppt,pptx,txt"
                        });
                        filters.push({
                            title: "video files",
                            extensions: "mp4,avi,rmvb"
                        });
                    }
                    return filters;
                }
            },
            // 设置某个特定的配置参数,option为参数名称
            setOption: function(up, file) {
                let self = this;
                //使用jquery的同步请求方式
                $.ajax({
                    url: self.axios.defaults.baseURL + "/api/base/v1/getAliyunOSSSignature",
                    type: "get",
                    async: false, //使用同步的方式,true为异步方式
                    headers: {
                        Authorization: "Bearer " + localStorage.getItem(appConfig.TOKEN_KEY)
                    }, //这里使用json对象
                    data:{
                        bucket: self.api
                    },
                    success: function(data) {
                        let params = get_upload_param(data, file.name);
                        params["multipart_params"].Filename = self.api + '/' + params["multipart_params"].key;
                        up.setOption({
                            url: params["url"],
                            multipart_params: params["multipart_params"]
                        });
                    }
                });
            },
            ossFileDelete: function(bucket,objectKey) {
                let self = this;
                self.axios({
                        method: "delete",
                        url: self.axios.defaults.baseURL + "/api/base/v1/deleteOssFile",
                        headers: {
                            "Content-Type": "application/json"
                        },
                        transformRequest: [
                            function(data) {
                                let ret = "";
                                for (let it in data) {
                                    ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
                                }
                                return ret;
                            }
                        ],
                        params: {
                            bucket: bucket,
                            key: objectKey
                        }
                    })
                    .then(function(response) {
                        if (response) {
                            let result = response.data;
                            if (result.code == 200) {
                                console.log(objectKey + "已删除");
                            }
                        }
                    })
                    .catch(function(err) {bucket
                        console.log("噢耶，报错咯");
                    });
            },
            fileItemDelete: function(fileId,objectKey,bucket) {
                console.log("我是删除"+fileId);
                let self = this;
                if (fileId) {
                    for (let i in self.uploader.files) {
                        if (self.uploader.files[i].id === fileId) {
                            self.uploader.files.splice(i, 1);
                            break;
                        }
                    }
                    for (let i in self.previewData) {
                        if (self.previewData[i].fileId === fileId) {
                            self.previewData.splice(i, 1);
                            break;
                        }
                    }
                }
                if (objectKey) {
                    let postParam = {
                        bucket: bucket,
                        key: objectKey
                    };
                    self.$confirm("当前文件已上传完毕，确认要删除吗?", "提示", {
                            confirmButtonText: "确定",
                            cancelButtonText: "取消",
                            type: "warning"
                        })
                        .then(() => {
                            self.axios({
                                    method: "delete",
                                    url: self.axios.defaults.baseURL + "/api/base/v1/deleteOssFile",
                                    headers: {
                                        "Content-Type": "application/json"
                                    },
                                    transformRequest: [
                                        function(data) {
                                            let ret = "";
                                            for (let it in data) {
                                                ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
                                            }
                                            return ret;
                                        }
                                    ],
                                    params: postParam
                                })
                                .then(function(response) {
                                    if (response) {
                                        let result = response.data;
                                        if (result.code == 200) {
                                            for (let i = 0; i < self.postData.length; i++) {
                                                if (objectKey == self.postData[i].object) {
                                                    self.postData.splice(i, 1);
                                                    console.log('self.postData');
                                                    console.log(self.postData);
                                                    self.$emit("reloadFiles", self.postData);
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                })
                                .catch(function(err) {
                                    console.log("噢耶，报错咯");
                                });
                        })
                        .catch(() => {
                            self.$message({
                                type: "info",
                                message: "已取消删除"
                            });
                        });
                }
            },
            download: function(url) {
                window.open('https://'+ this.bucket +'.oss-cn-qingdao.aliyuncs.com/'+ url);
            },
            resetData: function() {
                if (this.uploader != null) {
                    if (this.uploader.files != null) {
                        this.uploader.splice(0, this.uploader.files.length)
                        this.previewData = [];
                    }
                }
            },    
            // 复制变量copyVaule
            handleCopy (url) {
                const copyVaule = url;
                this.$confirm(`复制此文章链接${copyVaule}, 是否继续?`, '复制', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }).then(() => {
                    // 创建'虚拟'DOM
                    const input = document.createElement('input')
                    document.body.appendChild(input)
                    input.setAttribute('value', copyVaule)
                    input.select()
                    if (document.execCommand('copy')) {
                    document.execCommand('copy')
                    this.$message({
                    type: 'success',
                    message: '复制成功!'
                    })
                }
                // 删除'虚拟'DOM
                document.body.removeChild(input)
                })
            }

        },
        mounted: function() {
            let self = this;
            this.$nextTick(function() {
                self.uploader = new plupload.Uploader({
                    runtimes: "html5,flash,silverlight,html4",
                    browse_button: self.buttonIds.select,
                    //multi_selection: false,
                    container: document.getElementById(self.buttonIds.container),
                    flash_swf_url: "../../static/js/plupload/Moxie.swf",
                    silverlight_xap_url: "../../static/js/plupload/Moxie.xap",
                    multi_selection: self.multiFile,
                    url: "http://oss.aliyuncs.com",
                    // multipart_params: {
                    //     'Filename': '${filename}',
                    //     'key' : '${filename}',
                    //     'policy': policyBase64,
                    //     'OSSAccessKeyId': accessid,
                    //     'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
                    //     'signature': signature,
                    // },
                    filters: {
                        mime_types: this.initFilters(),
                        /* max_file_size: "1000mb", */ //
                        prevent_duplicates: true //不允许选取重复文件
                    },
                    // 初始化Plupload实例
                    init: {
                        PostInit: function() {
                            document.getElementById(self.buttonIds.upload).onclick = function() {
                                console.log('self.postData');
                                console.log(self.postData);
                                if (self.postData.length > 0 && !self.multiFile) {
                                    self.$confirm("确定替换已上传的文件吗?", "提示", {
                                            confirmButtonText: "确定",
                                            cancelButtonText: "取消",
                                            type: "warning"
                                        })
                                        .then(() => {
                                            self.uploader.start();
                                        })
                                } else {
                                    self.uploader.start();
                                }
                                return false;
                            };
                        },
                        // 选择文件，添加文件信息----此时文件未进行上传
                        FilesAdded: function(up, files) {
                            if (!self.multiFile) {
                                let file = _.cloneDeep(files[0]);
                                files = [];
                                files.push(file);
                                self.previewData = [];
                            }
                            plupload.each(files, function(file) {
                                let data = {};
                                //  file  为选择文件的信息
                                data.fileRealName = file.name;  
                                data.fileId = file.id;
                                data.isImage = true;
                                data.percent = 0;
                                self.previewImage(file, function(imgsrc, suffix) {
                                    data.imgsrc = imgsrc;
                                    if (!suffix) {
                                        data.isImage = false;
                                        data.imgsrc = imgsrc;
                                        data.fileStoreName = imgsrc;
                                        data.fileType = suffix;
                                    }
                                    self.previewData.push(data);
                                });
                            });
                        },
                        //  点击上传前
                        BeforeUpload: function(up, file) {
                            self.setOption(up, file);
                        },
                        //  点击上传后
                        UploadProgress: function(up, file) {
                            for (let i in self.previewData) {
                                if (self.previewData[i].fileId === file.id) {
                                    self.previewData[i].percent = file.percent;
                                    break;
                                }
                            }
                        },
                        // 上传之后，返回数据
                        FileUploaded: function(up, file, info) {
                            console.log(file);
                            if (info.status == 200) {
                                let data = new Object();
                                let responseData = JSON.parse(info.response);
                                self.bucket = responseData.bucket;
                                if (responseData) {
                                    //完成上传后，如果只允许单个文件时，将其他已上传数据删除
                                    if (!self.multiFile) {
                                        let each = self;
                                        $.each(self.postData, function(i, item) {
                                            each.ossFileDelete(responseData.bucket,item.object);
                                        });
                                        //清空要提交的数据
                                        self.postData = [];
                                    }
                                    data.bucket = responseData.bucket;
                                    data.object = file.name;
                                    data.fileRealName = file.name;
                                    data.fileType = responseData.mimeType;
                                    // data.fileStoreName = responseData.fileStoreName;
                                    data.fileStoreName = 'https://'+ responseData.bucket +'.oss-cn-qingdao.aliyuncs.com/'+ file.name;
                                    self.postData.push(data);
                                    self.$emit("reloadFiles", self.postData);
                                    self.fileItemDelete(file.id,null, null);
                                } else {
                                    alert("上传数据回调异常");
                                }
                            } else if (info.status == 203) {
                            } else {
                            }
                        },
                        Error: function(up, err) {
                            if (err.code == -600) {
                                alert("文件大小超出限制");
                            } else if (err.code == -601) {
                                alert("文件类型不支持 ");
                            } else if (err.code == -602) {
                                alert("当前文件已经添加过了 ");
                            } else {
                                alert("文件上传签名超时了，请刷新页面重新选择");
                            }
                        }
                    }
                });
                self.uploader.init();
            });
        }
    };
</script>

<style>
    .btn {
        color: #fff;
        background-color: #337ab7;
        border-color: #2e6da4;
        display: inline-block;
        padding: 6px 12px;
        margin-bottom: 0;
        font-size: 14px;
        font-weight: 400;
        line-height: 1.42857143;
        text-align: center;
        white-space: nowrap;
        text-decoration: none;
        vertical-align: middle;
        -ms-touch-action: manipulation;
        touch-action: manipulation;
        cursor: pointer;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        background-image: none;
        border: 1px solid transparent;
        border-radius: 4px;
        z-index: 0;
    }
    a.btn:hover {
        background-color: #3366b7;
    }
    .progress {
        margin-top: 2px;
        width: 200px;
        height: 14px;
        margin-bottom: 10px;
        overflow: hidden;
        background-color: #f5f5f5;
        border-radius: 4px;
        -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
        box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
    }
    .progress-bar {
        background-color: rgb(92, 184, 92);
        background-image: linear-gradient( 45deg, rgba(255, 255, 255, 0.14902) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.14902) 50%, rgba(255, 255, 255, 0.14902) 75%, transparent 75%, transparent);
        background-size: 40px 40px;
        box-shadow: rgba(0, 0, 0, 0.14902) 0px -1px 0px 0px inset;
        box-sizing: border-box;
        color: rgb(255, 255, 255);
        display: block;
        float: left;
        font-size: 12px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        transition-delay: 0s;
        transition-duration: 0.6s;
        transition-property: width;
        transition-timing-function: ease;
        width: 266.188px;
    }
    .upload-item {
        margin-right: 15px;
        width: 230px;
        float: left;
        position: relative;
    }
    .cover-show {
        position: absolute;
        top: 0%;
        left: 0%;
        width: 100%;
        height: 140px;
        background-color: black;
        z-index: 1001;
        -moz-opacity: 0.7;
        opacity: 0.7;
        filter: alpha(opacity=70);
        text-align: center;
        display: none;
    }
    .cover-show span {
        color: #fff;
        font-size: 12px;
        line-height: 20px !important;
        word-wrap: break-word;
    }
    .upload-item_text {
        position: relative;
        margin-bottom: 3px;
    }
    .upload-item_text a {
        color: #5a5e66;
        font-size: 12px;
        line-height: 20px;
    }
    .upload-item_text a.tit {
        display: block;
        width: 100%;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .upload-item_text .fl {
        width: 100%;
        padding-right: 130px;
        -webkit-box-sizing: border-box;
        -moz-box-sizing: border-box;
        box-sizing: border-box;
    }
    .upload-item_text .fr {
        position: absolute;
        right: 0;
        text-align: right;
        line-height: 24px;
        width: 130px;
        overflow: hidden;
    }
    .upload-item_text .fr a {
        color: #00bbbd;
        margin: 0 3px;
    }
    .upload-item_text .percent {
        display: inline-block;
        width: 40px;
        text-align: center;
    }
    .plupload {
        padding-top: 10px;
    }
</style>